package com.zbmy.plugin.im.server.core.back.processor;

import io.netty.channel.Channel;

import java.nio.ByteBuffer;
import java.util.Map;

import org.apache.commons.collections.MapUtils;


import org.apache.log4j.Logger;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.base.framework.utils.JsonUtils;
import com.base.framework.utils.RedisUtils;
import com.zbmy.plugin.im.server.core.NetShareInstance;
import com.zbmy.plugin.im.server.core.packet.ChatPacket;
import com.zbmy.plugin.im.server.core.protocol.MessageHolder;
import com.zbmy.plugin.im.server.core.protocol.ProtocolHeader;
import com.zbmy.plugin.im.server.core.session.UserSessionManger;
import com.zbmy.plugin.im.server.spring.SpringUtil;

/**
 * 
 * 登录消息处理  
 * @ClassName: LoginMessageProcessor    
 * @author Yangleping  
 * @date 2018年5月4日 下午3:03:21    
 * @version  v 1.0
 */
public class ChatMessageProcessor extends ShortLinkMessageDispact implements MessageProcessor {
	Logger logger = Logger.getLogger(ChatMessageProcessor.class);
	@SuppressWarnings("unchecked")
	@Override
	public void excute(MessageHolder messageHolder) {
		// 执行登入操作
		String body = messageHolder.getBody();
		if(StringUtils.isEmpty(body)){
			// 登入失败
			return;
		}
		// 反序列化
		ChatPacket loginPacket = JsonUtils.readValue(body, ChatPacket.class);
		if(loginPacket == null){
			// 登入失败
			return;
		}
		Channel channel = UserSessionManger.userToChannelOnlineMap.get(String.valueOf(loginPacket.getUserId()));
		if(channel == null){
			// 从redis中查询对方对应的serverId
			RedisUtils redisUtils = SpringUtil.getBean("redisUtils", RedisUtils.class);
			String imServerInfo = redisUtils.get(String.valueOf(loginPacket.getUserId()));
        	if(StringUtils.isEmpty(imServerInfo)){
        		// 该用户ID所在的IM服务器并不存在，表示该用户并未上线
        		// 保存离线消息，做其他处理工作
        		
        		return;
        	}
			Map<String,Object> imServerInfoMap = (Map<String,Object>)JsonUtils.readValue(imServerInfo, Map.class);
			String serverIp=MapUtils.getString(imServerInfoMap, "serverIp");
			if(StringUtils.isEmpty(serverIp)){
				// 该用户ID所在的IM服务器并不存在，表示该用户并未上线
        		// 保存离线消息，做其他处理工作
        		
        		return;
			}
			if(StringUtils.isNotEmpty(serverIp) && StringUtils.isEquals(serverIp,  NetShareInstance.serverIp)){
				// 该用户ID会话就在本机服务器
				responseMsg(channel, messageHolder);
				return;
			}
			try {
				dispactToOtherServer(serverIp, messageHolder);
			} catch (Exception e) {
				logger.error("消息服务器寻址转发失败", e);
			}
			// 发到queue1中 可以将mq分为10个
			/*
			MessageReq messageReq = new MessageReq();
			messageReq.setMsg(JsonUtils.writeValueAsString(String.valueOf(loginPacket.getUserId())));
			messageReq.setQueueName(QueueDefEnum.AUDIENCE_EVENT_RECORD_JOB_QUEUE.getQueueName());
			MqProducerService mqProducerService = SpringUtil.getBean("mqProducerService", MqProducerService.class);
			mqProducerService.sendMsg(messageReq);*/
		}
	}
	protected void responseMsg(Channel channel, MessageHolder sessageHolder){
		try {
			String content = sessageHolder.getBody();
			 byte[] array = content.getBytes("UTF-8");
			 int byteLen = array.length;
			 ByteBuffer directBuffer = ByteBuffer.allocate(byteLen + 9);   // 这里一定要注意，分配得大小一定要等于数据占用大小
			 directBuffer.putShort(ProtocolHeader.MAGIC);
			 directBuffer.put(sessageHolder.getStatus());
			 directBuffer.put(sessageHolder.getSign());
			 directBuffer.put(sessageHolder.getStatus());
			 directBuffer.putInt(byteLen);
			 directBuffer.put(array);
			 channel.write(directBuffer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
